Simplify CPP - Arrays

Arrays

What is an Array?

An array is a collection of elements of the same type stored in contiguous memory locations. It provides a way to store and access multiple values of the same type using a single variable name.

In C++, arrays are declared by specifying the data type of the elements, followed by the name of the array and the number of elements in square brackets. For example, to declare an array of integers with 5 elements:

int myArray[5];

How Does an Array Work?

When an array is declared, a block of contiguous memory locations is allocated to hold the elements of the array. The elements can be accessed using their index, which starts from 0 for the first element and goes up to the size of the array minus 1 for the last element.

For example, to assign a value to the second element of the array:

myArray[1] = 42;

To access the elements of the array in a loop, you can use the size of the array to control the number of iterations:

for (int i = 0; i < 5; i++) {
  myArray[i] = i * i;
}